package com.lsw.photoview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.lsw.R;
import com.lsw.config.CacheManager;
import com.lsw.photo.IBanner;
import com.lsw.photo.PubBanner;
import com.lsw.util.ImageTool;
import com.lsw.util.Md5Util;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 大图浏览页 Author:heiyue Email:heiyue623@126.com 2015-6-5上午9:30:34
 */
public class PhotoViewActivity extends FragmentActivity {

    public static final String IMAGE_URLS_ARR = "img_urls";
    public static final String IMAGE_POSITION = "img_position";
    public static final String IMAGE_TYPE_HEAD = "img_type_head";// 图片类型为头像
    public static List<? extends IBanner> images;
    private int currentPos;
    private TextView tvSize;
    private Activity context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Mars", "PhotoViewActivity.onCreate()");
        // getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        // WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            );
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.pub_activity_photo_view);
        context = this;
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        tvSize = (TextView) findViewById(R.id.tvSize);
        currentPos = getIntent().getIntExtra(IMAGE_POSITION, 0);
        if (images != null && images.size() > 0) {
            Adapter adapter = new Adapter();
            viewPager.setAdapter(adapter);
            if (currentPos >= 0 && currentPos < images.size()
                    && images.size() > 1) {
                tvSize.setText((currentPos + 1) + " / " + images.size());
                viewPager.setCurrentItem(currentPos);
            }
        }
        /**
         * 切换效果
         */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                tvSize.setText((arg0 + 1) + " / " + images.size());
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

    }

    /**
     * 打开大图浏览
     *
     * @param context
     * @param position
     * @param imgs
     */
    public static void startActivity(Context context, int position,
                                     List<? extends IBanner> imgs) {
        if (position < 0) {
            position = 0;
        }
        Intent intent = new Intent(context, PhotoViewActivity.class);
        intent.putExtra(IMAGE_POSITION, position);
        PhotoViewActivity.images = imgs;
        context.startActivity(intent);
    }

    public static void startActivity(Fragment fragment, int position,
                                     List<? extends IBanner> imgs) {
        if (position < 0) {
            position = 0;
        }
        Intent intent = new Intent(fragment.getActivity(), PhotoViewActivity.class);
        intent.putExtra(IMAGE_POSITION, position);
        PhotoViewActivity.images = imgs;
        fragment.startActivity(intent);
    }

    public static void startActivity(Context context, String imageUrl) {
        Intent intent = new Intent(context, PhotoViewActivity.class);
        intent.putExtra(IMAGE_POSITION, 0);
        List<PubBanner> childs = new ArrayList<PubBanner>();
        PubBanner child = new PubBanner();
        child.img = imageUrl;
        childs.add(child);
        PhotoViewActivity.images = childs;
        context.startActivity(intent);
    }

    class Adapter extends PagerAdapter {

        public Adapter() {
        }

        @Override
        public int getCount() {
            if (images != null) {
                return images.size();
            }
            return 0;
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            final IBanner item = images.get(position);
            PhotoView photoView = new PhotoView(container.getContext());
            container.addView(photoView, LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT);
            if (item != null) {
                String photoPath = item.getUrl();
                if (!TextUtils.isEmpty(photoPath)) {
                    if (photoPath.startsWith("http://")) {
                        // 网络图片
                        ImageLoader.getInstance().displayImage(photoPath,
                                photoView, CacheManager.getDefaultDisplay());
                    } else {
                        // 本地图片
                        ImageLoader.getInstance().displayImage(
                                Uri.fromFile(new File(photoPath)).toString(),
                                photoView,
                                CacheManager.getLocalDisplayerOptions4Upload());
                    }
                } else if (item.getResource() > 0) {
                    // 加载的是图片资源
                    ImageLoader.getInstance().displayImage(
                            "drawable://" + item.getResource(), photoView,
                            CacheManager.getLocalDisplayerOptions4Upload());
                }
            }
            photoView
                    .setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                        @Override
                        public void onViewTap(View view, float x, float y) {
                            finish();
                        }
                    });
            photoView.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    // showPopuWindow(item.getPhotoPath());
                    currentUrl = item.getUrl();
                    SavePhotoPopActivity.open(context, 1);
                    return true;
                }
            });
            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    // 菜单操作
                    if (SavePhotoPopActivity.isSave) {
                        // 保存菜单的操作
                        save(currentUrl);
                    }
                    break;

                default:
                    break;
            }
        }
    }

    private String currentUrl;

    /**
     * 保存到相册
     *
     * @param url
     */
    private void save(final String url) {
        String displayUrl = url;
        if (!url.startsWith("http://")) {
            displayUrl = Uri.fromFile(new File(url)).toString();
        }
        ImageLoader.getInstance().loadImage(displayUrl,
                new ImageLoadingListener() {

                    @Override
                    public void onLoadingStarted(String imageUri, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view,
                                                FailReason failReason) {

                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view,
                                                  Bitmap loadedImage) {
                        try {
                            // 保存到相册
                            String dir = CacheManager
                                    .getQrcodeDir(getApplicationContext());
                            ImageTool.saveJPGE_After(loadedImage,
                                    dir + Md5Util.md5(url) + ".jpg");
                            // 保存成功，通知系统更新
                            ImageTool.scanPhotos(dir + Md5Util.md5(url) + ".jpg", getApplicationContext());
                            // 保存成功
                            Toast.makeText(getApplicationContext(), "成功保存到相册",
                                    Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {

                    }
                });

    }
}
